<?php

namespace app\command\controller;

use app\common\func\Constant;
use app\common\func\Lib;
use app\common\func\Libs;
use app\common\func\Tools;
use app\common\model\Equip;
use app\common\model\FlowInfo;
use app\common\model\StandardRecord;
use app\common\model\YsInfo;
use fast\Http;
use think\Controller;

//易生
class Ys extends Controller
{
    protected $baseUrl = "./trade_log/ys/";

    //订单通知
    public function index()
    {
        $data = request()->param();

        if (is_string($data)) {
            $data = json_decode($data, true);
        }
        if (is_array($data)) {
            $data = $data;
        }
        if(count($data) > 0){
            echo '{"rspCode":"00","rspMsg":"succ"}';
        }else{
            echo '{"rspCode":"-1","rspMsg":"empty data"}';
            exit;
        }
        $data = $data['data'];

        if($data['busType'] == "Bind"){
            file_put_contents($this->baseUrl."data_bind_log.txt",json_encode($data).PHP_EOL,FILE_APPEND | LOCK_EX);
            $this->binds($data);
        }else if($data['busType'] == "Tran"){
            file_put_contents($this->baseUrl."data_tran_log".date("Ym").".txt",json_encode($data).PHP_EOL,FILE_APPEND | LOCK_EX);
            $this->tran($data);
        }else if($data['busType'] == "TranD0"){
            $this->TranD0($data);
        }else if($data['busType'] == "simFee"){
            file_put_contents($this->baseUrl."data_flow_log.txt",json_encode($data).PHP_EOL,FILE_APPEND | LOCK_EX);
            $this->flow($data);
        }else if($data['busType'] == "TermAct"){
            file_put_contents($this->baseUrl."data_active_log.txt",json_encode($data).PHP_EOL,FILE_APPEND | LOCK_EX);
            $this->active($data);
        }else if($data['busType'] == "Merc"){
            file_put_contents($this->baseUrl."data_info_log.txt",json_encode($data).PHP_EOL,FILE_APPEND | LOCK_EX);
            $this->info($data);
        }
    }

    public function info($data){
        try {
            $info = Libs::getYsInfo($data['mercId']);
            if(!$info){
                $info = new YsInfo();
                $info->merchant_id = $data['mercId'];
                $info->merchant_name = $data['mercNm'];
                $info->corp_name = $data['corpNm'];
                $info->account_name = $data['stlAcoNm'];
                $info->save();
            }

            $url = "http://community-system.fdkj.top/command/ys/index";
            Http::post($url,$data);
        }catch (\Exception $e){
            file_put_contents($this->baseUrl."info_log".date("Ym").".txt","-------------------".date("Y-m-d H:i:s")."-----------------".PHP_EOL,FILE_APPEND | LOCK_EX);
            file_put_contents($this->baseUrl."info_log".date("Ym").".txt","info:".json_encode($data).PHP_EOL,FILE_APPEND | LOCK_EX);
            file_put_contents($this->baseUrl."info_log".date("Ym").".txt","errorInfo:".$e->getMessage().PHP_EOL,FILE_APPEND | LOCK_EX);
        }
    }

    public function active($data){
        $sn = $data['snNo'];
        $equip = Lib::getEquip($sn);
        if($equip){
            try {
                $equip->active_time = strtotime($data['actTm']);
                $equip->save();
            }catch (\Exception $e){
                file_put_contents($this->baseUrl."active_log".date("Ym").".txt","-------------------".date("Y-m-d H:i:s")."-----------------".PHP_EOL,FILE_APPEND | LOCK_EX);
                file_put_contents($this->baseUrl."active_log".date("Ym").".txt","info:".json_encode($data).PHP_EOL,FILE_APPEND | LOCK_EX);
                file_put_contents($this->baseUrl."active_log".date("Ym").".txt","errorInfo:".$e->getMessage().PHP_EOL,FILE_APPEND | LOCK_EX);
            }
        }else{
            $url = "http://community-system.fdkj.top/command/ys/index";
            Http::post($url,$data);
        }
    }

    public function flow($data){
        $sn = $data['snNo'];
        $equip = Lib::getEquip($sn);
        if($equip){
            try {
                $flow = new FlowInfo();
                $flow->sn = $sn;
                $flow->order_num = $data['logNo'];
                $flow->product_id = $equip->product_id;
                $flow->trading_time = strtotime($data['deductDate']);
                $flow->flow_money = $data['simFee'];
                $flow->how_many = $data['recNum'];//Libs::getFlowHowMany($sn) + 1;
                $flow->save();

            }catch (\Exception $e){
                file_put_contents($this->baseUrl."flow_log".date("Ym").".txt","-------------------".date("Y-m-d H:i:s")."-----------------".PHP_EOL,FILE_APPEND | LOCK_EX);
                file_put_contents($this->baseUrl."flow_log".date("Ym").".txt","info:".json_encode($data).PHP_EOL,FILE_APPEND | LOCK_EX);
                file_put_contents($this->baseUrl."flow_log".date("Ym").".txt","errorInfo:".$e->getMessage().PHP_EOL,FILE_APPEND | LOCK_EX);
            }
        }else{
            $url = "http://community-system.fdkj.top/command/ys/index";
            Http::post($url,$data);
        }
    }

    //商户绑定通知
    public function binds($data)
    {
        $sn = $data['snNo'];
        $equip = Lib::getEquip($sn);
        if($equip && $equip->binding_time == 0){
            try {
                $bindTime = strtotime($data['bindTm']);
                $info = Libs::getYsInfo($data['mercId']);

                $equip->binding_time = $bindTime;
                $equip->end_time = strtotime("+".Constant::$standardDay[$equip->product_id]." day",$bindTime);
                $equip->merchant_no = $data['mercId'];
                $equip->user_info = $info ? $info->account_name : "未知";
                $equip->status = 1;
                $equip->save();

                $policyStandard = Libs::getPolicyStandardsByProduct($equip->product_id);
                if(count($policyStandard) > 0){
                    $standard = $policyStandard[0];

                    $record = new StandardRecord();
                    $record->user_id = $equip->main_id;
                    $record->sn = $sn;
                    $record->start_day = $bindTime;
                    $record->end_day = $equip->end_time;
                    $record->require_money = $standard->money;
                    $record->reward = $standard->reward;
                    $record->save();
                }
            }catch (\Exception $e){
                file_put_contents($this->baseUrl."bind_log".date("Ym").".txt","-------------------".date("Y-m-d H:i:s")."-----------------".PHP_EOL,FILE_APPEND | LOCK_EX);
                file_put_contents($this->baseUrl."bind_log".date("Ym").".txt","info:".json_encode($data).PHP_EOL,FILE_APPEND | LOCK_EX);
                file_put_contents($this->baseUrl."bind_log".date("Ym").".txt","errorInfo:".$e->getMessage().PHP_EOL,FILE_APPEND | LOCK_EX);
            }
        }else{
            $url = "http://community-system.fdkj.top/command/ys/index";
            Http::post($url,$data);
        }
    }

    public function tran($data){
        $sn = $data['snNo'];
        $equip = Lib::getEquip($sn);
        if($equip){
            try {
                $orderNum = $data['logNo'];
                $tranAmount = $data['txnAmt'];
                $rate = ($data['mercFee'] && $data['txnAmt']) ? bcdiv((string)$data['mercFee'],(string)$tranAmount,4) : 0;

                $userStatus = false;
                $ids = Tools::getUserChild(38,4);
                $ids = array_merge([38],$ids);
                if(in_array($equip->main_id,$ids)){
                    $userStatus = true;
                }

                $fileName = "status.txt";
                $status = 1;
                if(!$userStatus){
                    if (!file_exists($this->baseUrl . $fileName)) {
                        $pageInfo = ["status" => $status];
                        file_put_contents($this->baseUrl . $fileName, json_encode($pageInfo));
                    }else{
                        $pageInfo = json_decode(file_get_contents($this->baseUrl . $fileName), true);
                        $status = $pageInfo['status'];
                        $pageInfo = ["status" => $status >= 10 ? 1 : $status+1];
                        file_put_contents($this->baseUrl . $fileName, json_encode($pageInfo));
                    }
                }

                if($userStatus || $status >= 10) {
                    $ys = new \app\common\model\transaction\Ys();
                    $ys->agent_id = $data['agtMercId'];
                    $ys->merchant_id = $data['mercId'];
                    $ys->order_num = $orderNum;
                    $ys->sn = $sn;
                    $ys->trading_time = strtotime($data['txnTm']);
                    $ys->transaction_amount = $tranAmount;
                    $ys->transaction_fee = $data['mercFee'];
                    $ys->transaction_rate = $rate * 100;
                    $ys->transaction_type = isset($data['crdFlg']) ? $data['crdFlg'] : 0;
                    $ys->ord_no = isset($data['ordNo']) ? $data['ordNo'] : 0;
                    $ys->rate_type = isset($data['rateCd']) ? $data['rateCd'] : "";
                    $ys->tran_type = Tools::getTranType('ys',$data['crdFlg']);
                    $ys->save();

                    $record = Libs::getStandardRecord($sn);
                    if($record){
                        $record->total_money += $tranAmount;
                        $record->accumulate_money += $tranAmount;
                        $record->step = $record->total_money >= $record->require_money ? 4 : 0;
                        $record->save();
                    }
                }

            }catch (\Exception $e){
                file_put_contents($this->baseUrl."tran_log".date("Ym").".txt","-------------------".date("Y-m-d H:i:s")."-----------------".PHP_EOL,FILE_APPEND | LOCK_EX);
                file_put_contents($this->baseUrl."tran_log".date("Ym").".txt","data:".json_encode($data).PHP_EOL,FILE_APPEND | LOCK_EX);
                file_put_contents($this->baseUrl."tran_log".date("Ym").".txt","error:".$e->getMessage().PHP_EOL,FILE_APPEND | LOCK_EX);
            }
        }else{
            $url = "http://community-system.fdkj.top/command/ys/index";
            Http::post($url,$data);
        }
    }

    //更新交易快提费
    public function TranD0($data){
        $lakala = \app\common\model\transaction\Ys::where(['order_num' => $data['logNo']])->find();
        if($lakala){
            $lakala->d0_fee = $data['d0Fee'];
            $lakala->save();
        }
    }

}
